package setting

import (
	"github.com/go-ini/ini"
	"log"
	"time"
)

type App struct {
	Debug           int
	AppName         string
	Lang            string
	JwtSecret       string
	PageSize        int
	RuntimeRootPath string
	QrCodeSavePath  string
	ExportSavePath  string
	PrefixUrl       string
	ImageSavePath   string
	ImageMaxSize    int
	ImageAllowExts  []string

	LogSavePath string
	LogSaveName string
	LogFileExt  string
	TimeFormat  string
}

var AppSetting = &App{}

type Server struct {
	RunMode      string
	HttpPort     int
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
}

var ServerSetting = &Server{}

type Redis struct {
	Host        string
	Password    string
	MaxIdle     int
	MaxActive   int
	IdleTimeout time.Duration
}

var RedisSetting = &Redis{}

type Email struct {
	HOST        string
	PORT        int
	USERNAME    string
	PASSWORD    string
	FROMADDRESS string
	FROMNAME    string
	ADMINMAIL   string
}

var EmailSetting = &Email{}

type Logger struct {
	HOST string
	PORT int
}

var LoggerSetting = &Logger{}

func Setup(confPath string) {
	Cfg, err := ini.Load(confPath)
	if err != nil {
		log.Fatalf("Fail to parse '%s': %v", confPath, err)
	}

	// AppSetting
	err = Cfg.Section("app").MapTo(AppSetting)
	if err != nil {
		log.Fatalf("Cfg.MapTo AppSetting err: %v", err)
	}

	AppSetting.ImageMaxSize = AppSetting.ImageMaxSize * 1024 * 1024

	// Server
	err = Cfg.Section("server").MapTo(ServerSetting)
	if err != nil {
		log.Fatalf("Cfg.MapTo ServerSetting err: %v", err)
	}

	// Redis
	err = Cfg.Section("redis").MapTo(RedisSetting)
	if err != nil {
		log.Fatalf("Cfg.MapTo RedisSetting err: %v", err)
	}

	// Email
	err = Cfg.Section("email").MapTo(EmailSetting)

	ServerSetting.ReadTimeout = ServerSetting.ReadTimeout * time.Second
	ServerSetting.WriteTimeout = ServerSetting.WriteTimeout * time.Second
	RedisSetting.IdleTimeout = RedisSetting.IdleTimeout * time.Second
}
